<template>
  <el-upload class="avatar-uploader" action="#" :show-file-list="false" :http-request="upload" :before-upload="beforeAvatarUpload">
    <img v-if="src" :src="src" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    <el-progress v-show="isShow" :percentage="percent" status="success" :stroke-width="6"></el-progress>
  </el-upload>
</template>

<script>
// 导入腾讯云cos的SDK调用
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDc6KHxNWOzIL8drpWw5yavzmIXVCcldEZ', // 身份识别ID
  SecretKey: '5sOdgSyDCtJRJuDFBpCI6ewxg9LGtGMB' // 身份秘钥
})
// console.log(cos)
export default {
  name: 'UploadImg',
  props: {
    src: {
      type: String,
      default: ''
    }
  },

  data () {
    return {
      isShow: false,
      percent: 0

    }
  },
  methods: {
    upload ({ file }) {
      // console.log('上传的文件', file)
      this.isShow = true
      cos.putObject({
        Bucket: 'li-zhao-1308956165', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-beijing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD', // 存储模式=>标准模式
        Body: file, // 上传文件对象
        // progressData图片上传进度
        onProgress: function (progressData) {
          console.log(JSON.stringify(progressData))
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        if (!err) {
          console.log('上传成功', data)
          // this.imageUrl = `https://${data.Location}`
          this.$emit('update:src', `https://${data.Location}`)
          this.percent = 0
          this.isShow = false
        }
      })
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

